// 数据同步服务
const { postgresPool, redisClient } = require('../config/database');

class DataSyncService {
    constructor() {
        this.syncQueue = [];
        this.isProcessing = false;
        this.maxRetries = 3;
        this.retryDelay = 5000; // 5秒
    }

    // 记录同步操作
    async logSyncOperation(operation, entityType, entityId, oldData = null, newData = null) {
        const client = await postgresPool.connect();
        
        try {
            const query = `
                INSERT INTO sync_logs (operation, entity_type, entity_id, old_data, new_data)
                VALUES ($1, $2, $3, $4, $5)
                RETURNING id
            `;
            
            const values = [
                operation,
                entityType,
                entityId,
                oldData ? JSON.stringify(oldData) : null,
                newData ? JSON.stringify(newData) : null
            ];
            
            const result = await client.query(query, values);
            return result.rows[0].id;
        } finally {
            client.release();
        }
    }

    // 更新同步状态
    async updateSyncStatus(logId, status, errorMessage = null) {
        const client = await postgresPool.connect();
        
        try {
            const query = `
                UPDATE sync_logs 
                SET sync_status = $1, 
                    synced_at = $2,
                    error_message = $3
                WHERE id = $4
            `;
            
            const values = [
                status,
                status === 'completed' ? new Date() : null,
                errorMessage,
                logId
            ];
            
            await client.query(query, values);
        } finally {
            client.release();
        }
    }

    // 同步用户数据
    async syncUser(operation, userId, oldData = null, newData = null) {
        const logId = await this.logSyncOperation(operation, 'user', userId, oldData, newData);
        
        try {
            // 这里可以实现与其他系统的数据同步
            // 例如：同步到CRM系统、邮件系统等
            
            // 模拟同步操作
            await new Promise(resolve => setTimeout(resolve, 100));
            
            // 更新缓存
            if (operation === 'update' || operation === 'create') {
                await redisClient.setex(
                    `user:${userId}`,
                    1800, // 30分钟缓存
                    JSON.stringify(newData)
                );
            } else if (operation === 'delete') {
                await redisClient.del(`user:${userId}`);
            }
            
            await this.updateSyncStatus(logId, 'completed');
            console.log(`✅ 用户数据同步完成: ${operation} user ${userId}`);
        } catch (error) {
            await this.updateSyncStatus(logId, 'failed', error.message);
            console.error(`❌ 用户数据同步失败: ${operation} user ${userId}`, error);
            throw error;
        }
    }

    // 同步文章数据
    async syncArticle(operation, articleId, oldData = null, newData = null) {
        const logId = await this.logSyncOperation(operation, 'article', articleId, oldData, newData);
        
        try {
            // 这里可以实现与其他系统的数据同步
            // 例如：同步到搜索引擎、CDN、社交媒体等
            
            // 模拟同步操作
            await new Promise(resolve => setTimeout(resolve, 150));
            
            // 更新缓存
            if (operation === 'update' || operation === 'create') {
                await redisClient.setex(
                    `article:${articleId}`,
                    3600, // 1小时缓存
                    JSON.stringify(newData)
                );
                
                // 更新搜索索引
                await this.updateSearchIndex('article', articleId, newData);
            } else if (operation === 'delete') {
                await redisClient.del(`article:${articleId}`);
                await this.removeFromSearchIndex('article', articleId);
            }
            
            await this.updateSyncStatus(logId, 'completed');
            console.log(`✅ 文章数据同步完成: ${operation} article ${articleId}`);
        } catch (error) {
            await this.updateSyncStatus(logId, 'failed', error.message);
            console.error(`❌ 文章数据同步失败: ${operation} article ${articleId}`, error);
            throw error;
        }
    }

    // 更新搜索索引
    async updateSearchIndex(entityType, entityId, data) {
        const client = await postgresPool.connect();
        
        try {
            const content = this.extractSearchContent(data);
            const keywords = this.extractKeywords(data);
            
            const query = `
                INSERT INTO search_index (entity_type, entity_id, content, keywords)
                VALUES ($1, $2, $3, $4)
                ON CONFLICT (entity_type, entity_id) 
                DO UPDATE SET content = $3, keywords = $4, created_at = CURRENT_TIMESTAMP
            `;
            
            await client.query(query, [entityType, entityId, content, keywords]);
        } finally {
            client.release();
        }
    }

    // 从搜索索引中移除
    async removeFromSearchIndex(entityType, entityId) {
        const client = await postgresPool.connect();
        
        try {
            const query = 'DELETE FROM search_index WHERE entity_type = $1 AND entity_id = $2';
            await client.query(query, [entityType, entityId]);
        } finally {
            client.release();
        }
    }

    // 提取搜索内容
    extractSearchContent(data) {
        if (data.title && data.content) {
            return `${data.title} ${this.stripHtmlTags(data.content)}`;
        }
        return data.title || data.content || '';
    }

    // 提取关键词
    extractKeywords(data) {
        const keywords = [];
        
        if (data.keywords) {
            keywords.push(...data.keywords.split(',').map(k => k.trim()));
        }
        
        if (data.title) {
            keywords.push(...data.title.split(' ').filter(word => word.length > 2));
        }
        
        return keywords.join(',');
    }

    // 去除HTML标签
    stripHtmlTags(html) {
        return html.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
    }

    // 处理同步队列
    async processSyncQueue() {
        if (this.isProcessing) return;
        
        this.isProcessing = true;
        
        while (this.syncQueue.length > 0) {
            const syncTask = this.syncQueue.shift();
            
            try {
                await this.executeSyncTask(syncTask);
            } catch (error) {
                console.error('同步任务执行失败:', syncTask, error);
                
                // 重试逻辑
                if (syncTask.retryCount < this.maxRetries) {
                    syncTask.retryCount++;
                    setTimeout(() => {
                        this.syncQueue.unshift(syncTask);
                    }, this.retryDelay * syncTask.retryCount);
                }
            }
        }
        
        this.isProcessing = false;
    }

    // 执行同步任务
    async executeSyncTask(task) {
        const { operation, entityType, entityId, oldData, newData } = task;
        
        switch (entityType) {
            case 'user':
                await this.syncUser(operation, entityId, oldData, newData);
                break;
            case 'article':
                await this.syncArticle(operation, entityId, oldData, newData);
                break;
            default:
                throw new Error(`不支持的实体类型: ${entityType}`);
        }
    }

    // 添加同步任务到队列
    async queueSyncTask(operation, entityType, entityId, oldData = null, newData = null) {
        const task = {
            operation,
            entityType,
            entityId,
            oldData,
            newData,
            retryCount: 0,
            createdAt: new Date()
        };
        
        this.syncQueue.push(task);
        
        // 异步处理队列
        setImmediate(() => this.processSyncQueue());
    }

    // 获取同步状态报告
    async getSyncReport(days = 7) {
        const client = await postgresPool.connect();
        
        try {
            const query = `
                SELECT 
                    entity_type,
                    operation,
                    sync_status,
                    COUNT(*) as count
                FROM sync_logs 
                WHERE created_at >= CURRENT_DATE - INTERVAL '${days} days'
                GROUP BY entity_type, operation, sync_status
                ORDER BY entity_type, operation, sync_status
            `;
            
            const result = await client.query(query);
            
            return result.rows;
        } finally {
            client.release();
        }
    }

    // 清理旧的同步日志
    async cleanupOldLogs(daysToKeep = 30) {
        const client = await postgresPool.connect();
        
        try {
            const query = `
                DELETE FROM sync_logs 
                WHERE created_at < CURRENT_DATE - INTERVAL '${daysToKeep} days'
            `;
            
            const result = await client.query(query);
            
            console.log(`✅ 清理了 ${result.rowCount} 条旧的同步日志`);
            return result.rowCount;
        } finally {
            client.release();
        }
    }
}

module.exports = new DataSyncService();